import { _decorator, Component, Event, EventTouch, find, instantiate, Node, Prefab, UITransform, Vec2, Vec3 } from 'cc';
import engine from '../../core/Engine';
import { UIBaseView } from '../../core/ui/UIBaseView';
import { BlockItem } from './BlockItem';
const { ccclass, property } = _decorator;

@ccclass('MainGame')
export class MainGame extends UIBaseView {

    @property(Prefab) blockItem: Prefab = null

    private map = []

    private itemPool: BlockItem[][] = []

    private isMove = false

    private baseWidth = 100;
    private baseHeight = 100;

    protected onLoad(): void {
        this.node.on(Node.EventType.TOUCH_START, this.touchStart, this)
        this.node.on(Node.EventType.TOUCH_END, this.touchEnd, this)
        this.node.on(Node.EventType.TOUCH_MOVE, this.touchMove, this)
        this.node.on(Node.EventType.TOUCH_CANCEL, this.touchCancel, this)
    }

    start() {
        this.initMap()
        this.createrItem()
    }

    initMap() {
        for (let i = 0; i < 7; i++) {
            let arr = []
            for (let j = 0; j < 10; j++) {
                arr.push(j)
            }
            this.map.push(arr)
        }
    }

    private createrItem() {
        let basePos = {
            x: -this.baseWidth * this.map.length / 2 + this.baseWidth * 0.5,
            y: -this.baseHeight * this.map[0].length / 2 + this.baseHeight * 0.5,
        }
        let blockItem = null
        let item = null
        let itempoll = null
        for (let i = 0; i < this.map.length; i++) {
            itempoll = []
            for (let index = 0; index < this.map[i].length; index++) {
                item = instantiate(this.blockItem)
                item.parent = this.node
                item.setPosition(basePos.x + i * 100, basePos.y + index * 100)
                item.active = true
                blockItem = item.getComponent(BlockItem)
                blockItem.init(i, index)
                itempoll.push(blockItem)
            }
            this.itemPool.push(itempoll)
        }
    }


    private touchStart(e: EventTouch) {
        this.checkPos(e.getUILocation())
    }

    private touchEnd(e: EventTouch) {
        this.isMove = false
    }

    private touchMove(e: EventTouch) {
        if (!this.isMove) return
        this.checkPos(e.getUILocation(), true)
    }

    private touchCancel(e: EventTouch) {
        this.isMove = false
    }

    private checkPos(initPos: Vec2, isMove: boolean = false) {
        for (let index = 0; index < this.itemPool.length; index++) {
            for (let j = 0; j < this.itemPool[index].length; j++) {
                if (this.itemPool[index][j].checkPos(initPos, isMove)) {
                    this.isMove = true
                }
            }
        }
    }

    update(deltaTime: number) {

    }
}


